package com.yonyou.pmclouds.outter.tenant;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyou.iuap.tenant.sdk.TenantCenter;
import com.yonyou.iuap.tenant.sdk.UserCenter;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.conf.DeployTypeConfiguration;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.organization.entity.OrgTenantInfo;
import com.yonyou.pmclouds.productactive.rmiitf.LicenseQuery;
import com.yonyou.pmclouds.tenant.entity.TenantInfo;
import com.yonyou.pmclouds.tenant.entity.UserTenantInfo;
import com.yonyou.pmclouds.user.entity.UserSearchResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * 租户中心相关查询
 * <br>
 * 参阅 <a href="http://172.16.50.96/pages/viewpage.action?pageId=82719194">租户中心接口</a>
 */
@Slf4j
@Component
public class TenantInfoQuery {
    private ObjectMapper mapper = new ObjectMapper();
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private LicenseQuery query;

    public TenantInfoQuery() {
        // 设置反序列化时忽略vo中不存在的字段，放置平台偷偷的加字段，导致异常
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    // TODO 需要个缓存
    public boolean isTenantUserAutoToSystem(String tenantid, String sysId) {
        try {
            String result = TenantCenter.queryResState(tenantid, sysId);
            if (StringUtils.isEmpty(result)) {
                return false;
            }
            // 1000 为非自动同步用户，开启了应用内授权简单粗暴的处理一下。。。
            if (result.contains("1000")) {
                return false;
            }
        } catch (Exception ex) {
            log.error("租户中心查询失败", ex);
            return false;
        }
        return true;
    }

    public static final int LICENSE_OK = 0;
    public static final int LICENSE_USER_EXCEED = 1;
    public static final int LICENSE_SYSERR = 2;

    public List<TenantInfo> getTenantsOfUser(String userid, String sysid) {
        String result = TenantCenter.getCanLoginTenants(userid, sysid);
        if (StringUtils.isEmpty(result)) {
            return null;
        }
        try {
            UserTenantInfo infos = mapper.readValue(result, UserTenantInfo.class);
            if (!Integer.valueOf(1).equals(infos.getStatus()) || ArrayUtils.isEmpty(infos.getTenants())) {
                return null;
            }
            //                if (Integer.valueOf(0).equals(tenantInfo.getOutDate())) {
            //                }
            return new ArrayList<>(Arrays.asList(infos.getTenants()));
        } catch (IOException e) {
            return null;
        }
    }

    public int checkTenantLicense(String tenantid) throws BusinessException {

        //  添加系统id
        String result;
        if (this.isTenantUserAutoToSystem(tenantid, DeployTypeConfiguration.getSysId())) {
            result = UserCenter.searchUserListNotInUserIds(tenantid, Integer.toString(1),
                    Integer.toString(1), "", "userName", Collections.<String>emptyList());
        } else {
            result = UserCenter.searchAppUserListNotInUserIds(tenantid, DeployTypeConfiguration.getSysId(), Integer.toString(1),
                    Integer.toString(1), "", "userName", Collections.<String>emptyList());
        }
        if (StringUtils.isEmpty(result)) {
            return LICENSE_SYSERR;
        }
        try {
            UserSearchResultVO resultVO = mapper.readValue(result, UserSearchResultVO.class);
            if (resultVO != null && resultVO.getStatus() == 1) {
                // TODO 查询当前系统授权数，比较结果
                int num = query.getMaxUserCountOfTenant(tenantid, new Date());
                if (num < resultVO.getUsers().getTotalElements()) {
                    return LICENSE_USER_EXCEED;
                }
                return LICENSE_OK;
            }
        } catch (IOException e) {
            return LICENSE_SYSERR;
        }
        return LICENSE_SYSERR;
    }

    public TenantInfo queryTenantInfoById(String tenantid) throws BusinessException {

        String result = TenantCenter.getTenantById(tenantid);

        if(StringUtils.isEmpty(result))
            throw new BusinessException("友户通服务异常");

        try {
            OrgTenantInfo orgTenantInfo = mapper.readValue(result, OrgTenantInfo.class);

            if(orgTenantInfo != null)
                return orgTenantInfo.getTenant();
            return null;
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            return null;
        }
    }

}
